﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using LitJson;
using dbo;
using System.Net.Http;
using System.IO;
using System.Data;
/***********************/
/*********************/
namespace NewFarm
{

    class LogInController
    {
         
        public static LogInController instance;
        //private string ip = "127.0.0.1";
        private string ip = "192.168.197.72";
       // private string ip = "172.31.26.180";
        private int port = 11111;
        private Socket ServerSocket;
        List<string> lst=new List<string>();
        public Queue<object[]> UsersToValidateData;
        public static object obj = new object();
        public LogInController()
        {
            
            DBManager.Update("update CurrentOnLinePlayers set CurrentOnLinePlayers=0,MaxOnLinePlayers=0");
            Test();
            UsersToValidateData = new Queue<object[]>();
            //Initialize();
            instance = this;
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port);
            ServerSocket.Bind(ipe);
            ServerSocket.Listen(10000);
            ThreadPool.SetMinThreads(50, 50);
            ThreadPool.SetMaxThreads(100 ,400);
            new Thread(AcceptClients).Start();
            new Thread(ListenActivity).Start();
            new Thread(UpdateIfNewDay).Start();
            new Thread(ValidateData).Start();
            //new Thread(SendCheckDataToController).Start();
           // Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().StartInfo.FileName);
        }
        void Test()
        {
            /*************************************
             Assembly ass = Assembly.LoadFrom("FarmServer.exe");
             Type ty = ass.GetType("FarmServer.LogInController");
             MethodInfo mi = ty.GetMethod("Test");
             object f = mi.Invoke(this, new object[] { });
             Console.WriteLine(f);
             **************************************/
            Console.WriteLine((SQLEnum)(48));
        }
        void SendCheckDataToController() 
        {
            Socket SocketForController = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketForController.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 33333));
            while (true)
            {
                byte[] buffer = Encoding.UTF8.GetBytes("1");
                SocketForController.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, delegate { },null);
                Thread.Sleep(5000);
            }
        }
        void Initialize() 
        {
            JsonData jd1 = new JsonData();
            jd1.SetJsonType(JsonType.Array);
            for (int i = 0; i < 200;i++)
            {
                jd1.Add(0);
            }
            string info0 = jd1.ToJson();
            string info1 = jd1.ToJson();
            
            JsonData Level = new JsonData();
            Level.SetJsonType(JsonType.Array);
            for (int k = 0; k < 200;k++ )
            {
                JsonData dt = new JsonData();
                dt["ZeroStar"] = 0;
                dt["OneStar"] = 0;
                dt["TwoStar"] = 0;
                dt["ThreeStar"] = 0;
                Level.Add(dt);
            }
            string info2 = Level.ToJson();

            JsonData Items = new JsonData();
            Items["ColorItem"] = 0;
            Items["MagicItem"] = 0;
            Items["HammerItem"] = 0;
            Items["CrossItem"] = 0;
            Items["ExchangeItem"] = 0;
            Items["LineItem"] = 0;
            string info3 = Items.ToJson();

            JsonData StepOrTime = new JsonData();
            StepOrTime.SetJsonType(JsonType.Array);
            for (int i = 0; i < 200;i++)
            {
                StepOrTime.Add(0);
            }
            string info4 = StepOrTime.ToJson();

            JsonData WatchAds = new JsonData();
            WatchAds["DailyRewardUIAds"] = 0;
            JsonData Relive = new JsonData();
            Relive.SetJsonType(JsonType.Array);
            for (int i = 0; i < 200; i++)
            {
                Relive.Add(0);
            }
            WatchAds["FailToContinueAds"] = Relive;
            string info5 = WatchAds.ToJson();

            JsonData BuyProduct = new JsonData();
            BuyProduct["com.crushyvegie.somecoins"] = 0;
            BuyProduct["com.crushyvegie.abagofcoins"] = 0;
            BuyProduct["com.crushyvegie.achestofcoins"] = 0;
            BuyProduct["com.crushyvegie.apileofcoins"] = 0;
            BuyProduct["com.crushyvegie.tonsofcoins"] = 0;
            BuyProduct["com.crushyvegie.inexhaustibleCoins"] = 0;
            BuyProduct["com.crushyvegie.smallpackageofgoods"] = 0;
            BuyProduct["com.crushyvegie.largepackageofgoods"] = 0;
            BuyProduct["com.crushyvegie.giantpackageofgoods"] = 0;
            BuyProduct["com.crushyvegie.smallpackageofitems"] = 0;
            BuyProduct["com.crushyvegie.largepackageofitems"] = 0;
            BuyProduct["com.crushyvegie.giantpackageofitems"] = 0;

            BuyProduct["com.crushyvegie.greatdealpackage"] = 0;
            
            string info6 = BuyProduct.ToJson();

            JsonData BuyActivityInfo = new JsonData();
            BuyActivityInfo["Count"] = 0;
            string info7 = BuyActivityInfo.ToJson();

            JsonData CollectActivityInfo = new JsonData();
            CollectActivityInfo.SetJsonType(JsonType.Array);
            for (int i = 0; i < 200;i++ )
            {
                CollectActivityInfo.Add(0);
            }
            string info8 = CollectActivityInfo.ToJson();

            JsonData MissionInfo = new JsonData();
            MissionInfo.SetJsonType(JsonType.Array);
            for (int i = 0; i < 20;i++ )
            {
                MissionInfo.Add(0);
            }
            string info9 = MissionInfo.ToJson();
            DBManager.Update(string.Format("update info set LevelEnterInfo='{0}',LevelSuccessInfo='{1}',LevelAgainStarsInfo='{2}',UseItemInfo='{3}',LevelBuyStepOrTimeInfo='{4}',LevelWatchAdsInfo='{5}',ProductBuySuccessInfo='{6}',BuyActivitySuccessInfo='{7}',CollectActivityInfo='{8}',MissionInfo='{9}'", info0, info1, info2, info3, info4, info5, info6, info7, info8, info9));

        }
        void AcceptClients()
        {
            while (true)
            {
                
                 try
                 {
                     Socket ClientSocket = ServerSocket.Accept();
                     User user = new User(ClientSocket);
                     ChangeWithLock(true);
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine("!!!!!!!!!!!!!!Exception Occured When Just Accepted A Player!!!!!!!!!!!!!!!");
                     Console.WriteLine("*************AcceptClientsBegin******************");
                     Console.WriteLine("ErrorTime:" + DateTime.Now);
                     Console.WriteLine("ErrorMessage:" + e.Message);
                     Console.WriteLine("ErrorStackTrace:" + e.StackTrace);
                     Console.WriteLine("ErrorTargetSite:" + e.TargetSite);
                     Console.WriteLine("ErrorSource:" + e.Source);
                     Console.WriteLine("*************AcceptClientsEnd******************");
                 }
            }
        }
        
        public void ChangeWithLock(bool IsPlus) 
        {
         lock(obj)
         {
             if (IsPlus)
             {
                 DataRowCollection drc = DBManager.Select("select MaxOnLinePlayers,CurrentOnLinePlayers from CurrentOnLinePlayers");
                 int CurrentOnLinePlayers = (int)drc[0][1];
                 int MaxOnLinePlayers = (int)drc[0][0];
                 CurrentOnLinePlayers += 1;
                 if (CurrentOnLinePlayers > MaxOnLinePlayers)
                 {
                     MaxOnLinePlayers = CurrentOnLinePlayers;
                 }
                 DBManager.Update(string.Format("update CurrentOnLinePlayers set CurrentOnLinePlayers={0},MaxOnLinePlayers={1}", CurrentOnLinePlayers, MaxOnLinePlayers));
             }
             else 
             {
                 DataRowCollection drc = DBManager.Select("select CurrentOnLinePlayers from CurrentOnLinePlayers");
                 int CurrentOnLinePlayers = (int)drc[0][0];
                 CurrentOnLinePlayers -= 1;
                 DBManager.Update(string.Format("update CurrentOnLinePlayers set CurrentOnLinePlayers={0}", CurrentOnLinePlayers));
             }
         }
        }
        void ListenActivity()
        {
            while (true)
            {
                try
                {
                    DataRowCollection drc = DBManager.Select("select Id,Type,EndTime from currentactivity ");
                    if (drc.Count==2)
                    {
                        for (int i = 0; i < drc.Count; i++)
                        {
                            int a_id = (int)drc[i][0];
                            int a_type = (int)drc[i][1];
                            DateTime EndTime = (DateTime)drc[i][2];
                            DateTime CurrentTime = DateTime.Now;
                            if (CurrentTime >= EndTime)
                            {
                                DBManager.Delete(string.Format("delete from currentactivity where Type={0}", a_type));
                                if (a_type == 1)
                                {
                                    DBManager.Update("update player set TargetCollectedNumber=0,ActivityRewardState=0");
                                    FindActivity1();
                                }
                                else if (a_type == 2)
                                {
                                    FindActivity2();
                                }
                            }
                        }
                    }
                    else if(drc.Count==1)
                    {
                        int a_type = (int)drc[0][1];
                        DateTime EndTime = (DateTime)drc[0][2];
                        DateTime CurrentTime = DateTime.Now;
                        if (CurrentTime >= EndTime)
                        {
                            DBManager.Delete(string.Format("delete from currentactivity where Type={0}", a_type));
                        }
                        if (a_type == 1)
                        {
                            FindActivity2();
                        }
                        else FindActivity1();
                    }
                    else
                    {
                        FindActivity1();
                        FindActivity2();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("*****$exception begin$******");
                    Console.WriteLine("ErrorTime:" + DateTime.Now);
                    Console.WriteLine("ErrorMessage:" + e.Message);
                    Console.WriteLine("ErrorStackTrace:" + e.StackTrace);
                    Console.WriteLine("ErrorTargetSite:" + e.TargetSite);
                    Console.WriteLine("ErrorSource:" + e.Source);
                    Console.WriteLine("*****$exception end$******");
                }
                Thread.Sleep(1200000);//每个20分钟检测
            }
        }
        void FindActivity1()
        {
            DataRowCollection drc = DBManager.Select("select * from activity1 order by StartTime ASC");
            object[] Columns = null;
            for (int i = 0; i < drc.Count; i++)
            {
                object[] objs = drc[i].ItemArray;
                DateTime StartTime = DateTime.Parse(objs[11].ToString());
                DateTime EndTime = DateTime.Parse(objs[12].ToString());
                for (int j = 0; j < objs.Length; j++)
                {
                    if (StartTime <= DateTime.Now && EndTime > DateTime.Now)
                    {
                        Columns = objs;
                        break;
                    }
                }
            }
            if (Columns != null)
            {
                DBManager.Insert(string.Format("insert into currentactivity (Id,Type,StartTime,EndTime) values ({0},1,'{1}','{2}')", (int)Columns[0], DateTime.Parse(Columns[11].ToString()), DateTime.Parse(Columns[12].ToString())));
            }
        }
        void FindActivity2()
        {
            DataRowCollection drc = DBManager.Select("select * from activity2 order by StartTime ASC");
            object[] Columns = null;
            for (int i = 0; i < drc.Count; i++)
            {
                object[] objs = drc[i].ItemArray;
                DateTime StartTime = DateTime.Parse(objs[16].ToString());
                DateTime EndTime = DateTime.Parse(objs[17].ToString());
                for (int j = 0; j < objs.Length; j++)
                {
                    if (StartTime <= DateTime.Now && EndTime > DateTime.Now)
                    {
                        Columns = objs;
                        break;
                    }
                }
            }

            if (Columns != null)
            {
                DBManager.Insert(string.Format("insert into currentactivity (Id,Type,StartTime,EndTime) values ({0},2,'{1}','{2}')", (int)Columns[0], DateTime.Parse(Columns[16].ToString()), DateTime.Parse(Columns[17].ToString())));
            }


        }
        void UpdateIfNewDay()//每天s到某一个时间点更新玩家数据
        {
            while (true)
            {
                try 
                {
                    DateTime CurrentTime = DateTime.Now;
                    int hour = CurrentTime.Hour;
                    int minute = CurrentTime.Minute;
                    int second = CurrentTime.Second;
                    if (hour == 00 && minute == 00)
                    {
                        Console.WriteLine("data base updated at dawn!!!!");
                        DataRowCollection drc = DBManager.Select(string.Format("select DailyRewardState,DailyRewardCount,Id from player "));
                        for (int i = 0; i < drc.Count; i++)
                        {
                            int state = (int)drc[i][0];
                            int daycount = (int)drc[i][1];
                            int id = (int)drc[i][2];
                            if (daycount == 8)
                            {
                                daycount = 1;
                            }
                            else
                            {
                                if (state == 0)
                                {
                                    daycount = 1;

                                }
                                else daycount += 1;
                            }
                            DBManager.Update(string.Format("update player set DailyRewardState=0,PresentPowerState=0,DailyRewardCount={0} where Id={1}", daycount, id));
                        }
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine("*************UpdateIfNewDayBegin**********");
                    Console.WriteLine("ErrorMessage:" + e.Message);
                    Console.WriteLine("ErrorStackTrace:" + e.StackTrace);
                    Console.WriteLine("ErrorTargetSite:" + e.TargetSite);
                    Console.WriteLine("ErrorSource:" + e.Source);
                    Console.WriteLine("*************UpdateIfNewDayEnd**********");
                
                }
                Thread.Sleep(60000);//每个1分钟检测
            }
        }
        void ValidateData() 
        {
          while(true)
          {
              Thread.Sleep(100);
              if (UsersToValidateData.Count>0)
              {
                  object[] objs = UsersToValidateData.Dequeue();
                  object param=objs;
                  ThreadPool.QueueUserWorkItem(new WaitCallback(GetDataWithHttpRequest),param);
              }
          }
          
        }
        void GetDataWithHttpRequest(object data)//访问http服务器
        {
            try 
            {
                object[] objs = data as object[];
                Socket UserSocket = (Socket)objs[0];
                int Id = (int)objs[1];
                string DataToValidate = (string)objs[2];
                int ReqId = (int)objs[3];
                int DataId = (int)objs[4];
                string Version = (string)objs[5];
                int priority = 0;
                DataRowCollection drc = null;
                if (priority == 0)//从fromclient查找。若存在，则上次验证出现了问题或者新增加的数据。
                {
                    drc = DBManager.Select(string.Format("select * from fromclient where id={0} && DataId={1}", Id, DataId));
                    if (drc.Count != 0)
                    {
                        object[] colmns = drc[0].ItemArray;
                        JsonData jd = new JsonData();
                        jd["receipt-data"] = (string)DataToValidate;
                        StreamContent content3 = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(jd.ToJson())));
                        Uri uri = new Uri("https://buy.itunes.apple.com/verifyReceipt");//正式购买地址
                        if(Version=="1.0.3")//审核通过后改成1.0.4
                        {
                           uri = new Uri("https://sandbox.itunes.apple.com/verifyReceipt");//沙盒购买地址
                           Console.WriteLine("Current Version:" + Version);
                        }
                        HttpClient client = new HttpClient();
                        HttpResponseMessage ResponseMsg = client.PostAsync(uri, content3).Result;
                        string result = ResponseMsg.Content.ReadAsStringAsync().Result;
                        DBManager.Delete(string.Format("delete from fromclient where id={0} && DataId={1}", Id, DataId));
                        DBManager.Insert(string.Format("insert into fromapple (Id,DataFromApple,DataId,ReqId) values ({0},'{1}',{2},{3})", Id, result, DataId, ReqId));
                    }
                    priority = 1;
                }
                if (priority == 1)//从fromapple查找。若存在，把商品发给玩家。
                {
                    drc = DBManager.Select(string.Format("select * from fromapple where id={0} && DataId={1}", Id, DataId));
                    if (drc.Count != 0)
                    {
                        int State = (int)drc[0][4];
                        object[] colmns = drc[0].ItemArray;
                        int _ReqId = (int)colmns[3];
                        SQLEnum ReqType = (SQLEnum)_ReqId;
                        int _id = (int)colmns[0];
                        int _DataId = (int)colmns[2];
                        string DataFromApple = (string)colmns[1];
                        JsonData boss = JsonMapper.ToObject(DataFromApple);
                        int status = (int)boss["status"];
                        if (status == 0)//数据验证成功
                        {
                            JsonData receipt = boss["receipt"];
                            JsonData info = receipt["in_app"][0];
                            string ProId = (string)info["product_id"];
                            /***********统计购买成功数*************/
                            drc = DBManager.Select("select ProductBuySuccessInfo,BuyActivitySuccessInfo from info");
                            JsonData pbsi = JsonMapper.ToObject((string)drc[0][0]);
                            JsonData basi = JsonMapper.ToObject((string)drc[0][1]);
                            int buycount = (int)pbsi[ProId];
                            int TotalBuyCount = (int)basi["Count"];
                            if (ReqType == SQLEnum.购买了一个商品)
                            {
                                buycount += 1;
                                pbsi[ProId] = buycount;
                            }
                            else if (ReqType == SQLEnum.首次充值购买按钮点击)
                            {
                                TotalBuyCount += 1;
                                basi["Count"] = TotalBuyCount;
                            }
                            DBManager.Update(string.Format("update info set ProductBuySuccessInfo='{0}',BuyActivitySuccessInfo='{1}'", pbsi.ToJson(), basi.ToJson()));
                            /***************************************/
                            JsonData jd = new JsonData();
                            jd.SetJsonType(JsonType.Array);
                            DBManager.Update(string.Format("update fromapple set State=1 where Id={0}&&DataId={1}", _id, _DataId));
                            drc = DBManager.Select(string.Format("select Gold,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where id={0}", _id));
                            object[] BasicProperty = drc[0].ItemArray;
                            if (ReqType == SQLEnum.购买了一个商品)
                            {
                                drc = DBManager.Select(string.Format("select * from product where ProductId='{0}'", ProId));
                                object[] array = drc[0].ItemArray;
                                string CmdText1 = "update player set ";
                                int index = 0;
                                for (int i = 1; i < 8; i++)
                                {
                                    int num = (int)array[i];
                                    if (num > 0)
                                    {
                                        JsonData d = new JsonData();
                                        d["Id"] = i - 1;
                                        d["Count"] = num;
                                        int ToTalNum = (int)BasicProperty[i - 1] + num;
                                        if (index != 0)
                                        {
                                            CmdText1 += ",";
                                        }
                                        CmdText1 += GetProductName(i - 1) + "=" + ToTalNum;
                                        jd.Add(d);
                                        index++;
                                    }
                                }
                                CmdText1 += " where Id=" + _id;
                                if (State == 0)
                                {
                                    DBManager.Update(CmdText1);
                                }
                                JsonData PlayerProperty = new JsonData();
                                PlayerProperty.SetJsonType(JsonType.Array);
                                drc = DBManager.Select(string.Format("select Gold,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where id={0}", _id));
                                object[] objs2 = drc[0].ItemArray;
                                for (int i = 0; i < objs2.Length; i++)
                                {
                                    PlayerProperty.Add(objs2[i]);
                                }
                                JsonData MsgData = new JsonData();
                                MsgData["DataId"] = _DataId;
                                MsgData["msg"] = jd;
                                MsgData["Property"] = PlayerProperty;
                                JsonData MyBoss = new JsonData();
                                MyBoss["type"] = (int)SQLEnum.购买了一个商品;
                                MyBoss["msg"] = MsgData;
                                try
                                {
                                    byte[] buffer = Encoding.UTF8.GetBytes(MyBoss.ToJson());
                                    UserSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (IAsyncResult ir) => { }, null);
                                    Console.WriteLine("Successfully Send Verifyed Apple Data:"+MyBoss.ToJson());
                                }
                                catch
                                {


                                }
                            }
                            else if (ReqType == SQLEnum.首次充值购买按钮点击)
                            {
                                drc = DBManager.Select("select * from activity2 where id=(select id from currentactivity where Type=2 ) ");
                                if (drc.Count != 0)
                                {
                                    if (ProId == "com.crushyvegie.greatdealpackage")
                                    {
                                        DBManager.Update(string.Format("update player set FristBuyState=1 where Id={0}", _id));
                                    }
                                    drc = DBManager.Select("select * from activity2 where id=(select id from currentactivity where Type=2 ) ");
                                    object[] objs1 = drc[0].ItemArray;
                                    object[] array = new object[12];
                                    string CmdText = "update player set ";
                                    for (int i = 0; i < array.Length; i++)
                                    {
                                        array[i] = objs1[i + 3];
                                    }
                                    JsonData jd1 = null;
                                    string TempName = null;
                                    JsonData MyBossData = new JsonData();
                                    MyBossData.SetJsonType(JsonType.Array);
                                    for (int j = 0; j < array.Length; j++)
                                    {
                                        if (j % 2 == 0)
                                        {
                                            jd1 = new JsonData();
                                            int _code = a_GetTypeCode((string)array[j]);
                                            jd1["Id"] = _code;
                                            string Name = GetStringName3(_code);
                                            TempName = Name;
                                            CmdText += Name + "=";
                                        }
                                        else
                                        {
                                            int num = 0;
                                            switch (TempName)
                                            {
                                                case "Gold":
                                                    num = (int)BasicProperty[0];
                                                    break;
                                                case "LineItem":
                                                    num = (int)BasicProperty[1];
                                                    break;
                                                case "ColorItem":
                                                    num = (int)BasicProperty[3];
                                                    break;
                                                case "MagicItem":
                                                    num = (int)BasicProperty[2];
                                                    break;
                                                case "ExchangeItem":
                                                    num = (int)BasicProperty[4];
                                                    break;
                                                case "HammerItem":
                                                    num = (int)BasicProperty[5];
                                                    break;
                                                case "CrossItem":
                                                    num = (int)BasicProperty[6];
                                                    break;
                                            }
                                            int TempNum = (int)array[j] + num;
                                            jd1["Count"] = (int)array[j];
                                            CmdText += TempNum;
                                            if (j != array.Length - 1)
                                            {
                                                CmdText += ",";
                                            }
                                            MyBossData.Add(jd1);
                                        }
                                    }
                                    CmdText += " where id=" + _id;
                                    if (State == 0)
                                    {
                                        DBManager.Update(CmdText);
                                    }
                                    drc = DBManager.Select(string.Format("select Gold,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where id={0}", _id));
                                    objs1 = drc[0].ItemArray;
                                    JsonData Properties = new JsonData();
                                    Properties.SetJsonType(JsonType.Array);
                                    for (int i = 0; i < objs1.Length; i++)
                                    {
                                        Properties.Add(objs1[i]);
                                    }
                                    JsonData data1 = new JsonData();
                                    data1["list"] = MyBossData;
                                    data1["property"] = Properties;
                                    data1["DataId"] = _DataId;
                                    JsonData _dt = new JsonData();
                                    _dt["type"] = (int)SQLEnum.首次充值购买按钮点击;
                                    _dt["msg"] = data1;
                                    try
                                    {
                                        byte[] buffer = Encoding.UTF8.GetBytes(_dt.ToJson());
                                        UserSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (IAsyncResult ir) => { }, null);
                                        Console.WriteLine("Successfully Send Verifyed Apple Data:" + _dt.ToJson());
                                    }
                                    catch
                                    {


                                    }
                                }
                            }

                        }
                        else//数据验证失败
                        {
                            if (ReqType == SQLEnum.购买了一个商品)
                            {
                                JsonData MsgData = new JsonData();
                                MsgData["DataId"] = -1;
                                MsgData["OrigDataId"] = _DataId;
                                JsonData MyBoss = new JsonData();
                                MyBoss["type"] = (int)SQLEnum.购买了一个商品;
                                MyBoss["msg"] = MsgData;
                                try
                                {
                                    byte[] buffer = Encoding.UTF8.GetBytes(MyBoss.ToJson());
                                    UserSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (IAsyncResult ir) => { }, null);
                                    Console.WriteLine("Successfully Send UnVerifyed Apple Data:" + MyBoss.ToJson());
                                }
                                catch
                                {


                                }
                            }
                            else if (ReqType == SQLEnum.首次充值购买按钮点击)
                            {
                                JsonData data1 = new JsonData();
                                data1["DataId"] = -1;
                                data1["OrigDataId"] = _DataId;
                                JsonData _dt = new JsonData();
                                _dt["type"] = (int)SQLEnum.首次充值购买按钮点击;
                                _dt["msg"] = data1;
                                try
                                {
                                    byte[] buffer = Encoding.UTF8.GetBytes(_dt.ToJson());
                                    UserSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (IAsyncResult ir) => { }, null);
                                    Console.WriteLine("Successfully Send UnVerifyed Apple Data:" + _dt.ToJson());
                                }
                                catch
                                {


                                }
                            }

                        }
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.TargetSite);
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Source);
            
            }
            
        }
        int a_GetTypeCode(string name)//获取活动元素的编号
        {
            int num = -1;
            switch (name)
            {
                case "苹果":
                    num = 0;
                    break;
                case "蓝莓":
                    num = 1;
                    break;
                case "萝卜":
                    num = 2;
                    break;
                case "奖励障碍":
                    num = 3;
                    break;
                case "琥珀":
                    num = 4;
                    break;
                case "染色块"://(24-29)
                    num = 5;
                    break;
                case "鸡蛋":
                    num = 6;
                    break;
                case "茄子":
                    num = 7;
                    break;
                case "爆炸特效"://(18-23)
                    num = 8;
                    break;
                case "礼物盒"://(30,35)
                    num = 9;
                    break;
                case "冰块":
                    num = 10;
                    break;
                case "铁桶":
                    num = 11;
                    break;
                case "直线特效"://(6-17)
                    num = 12;
                    break;
                case "魔力块":
                    num = 13;
                    break;
                case "栗子":
                    num = 14;
                    break;
                case "梨":
                    num = 15;
                    break;
                case "锁链障碍":
                    num = 16;
                    break;
                case "西红柿":
                    num = 17;
                    break;
                case "水桶":
                    num = 18;
                    break;
                case "魔力":
                    num = 4;
                    break;
                case "金币":
                    num = 0;
                    break;
                case "染色":
                    num = 2;
                    break;
                case "直线":
                    num = 3;
                    break;
                case "手":
                    num = 5;
                    break;
                case "铲子":
                    num = 6;
                    break;
                case "火箭":
                    num = 1;
                    break;
            }
            return num;
        }
        string GetStringName3(int RewardType) //名字转换函数1
        {
            /****
          "icon_item_coin",         //0
          "icon_item_crossClear",   //1
          "icon_item_dye",          //2
          "icon_item_line",         //3
          "icon_item_magical",      //4
          "icon_item_move",         //5
          "icon_item_oneClear",     //6
          ***/
            string ItemName = null;
            switch (RewardType)
            {
                case 4:
                    ItemName = "MagicItem";
                    break;
                case 0:
                    ItemName = "Gold";
                    break;
                case 2:
                    ItemName = "ColorItem";
                    break;
                case 3:
                    ItemName = "LineItem";
                    break;
                case 5:
                    ItemName = "ExchangeItem";
                    break;
                case 6:
                    ItemName = "HammerItem";
                    break;
                case 1:
                    ItemName = "CrossItem";
                    break;
            }

            return ItemName;
        }
        string GetProductName(int Id) //名字转换函数1
        {
            /****
        Gold;//0
        LineItem;//1
        MagicItem;//2
        ColorItem;//3
	    ExchangeItem;//4
	    HammerItem;//5
	    CrossItem;//6
          ***/
            string ItemName = null;
            switch (Id)
            {
                case 2:
                    ItemName = "MagicItem";
                    break;
                case 0:
                    ItemName = "Gold";
                    break;
                case 3:
                    ItemName = "ColorItem";
                    break;
                case 1:
                    ItemName = "LineItem";
                    break;
                case 4:
                    ItemName = "ExchangeItem";
                    break;
                case 5:
                    ItemName = "HammerItem";
                    break;
                case 6:
                    ItemName = "CrossItem";
                    break;
            }

            return ItemName;
        }
    }
    public enum SQLEnum
    {
        数据同步 ,
        #region 选关界面
        进入选关场景,
        准备进入游戏,
        #endregion
        获取排行榜,
        #region 进入大关选择界面
        进入大关选择界面,
        #endregion
        #region 通过关卡界面
        通过关卡,
        #endregion
        #region 关卡失败界面
        关卡失败,
        #endregion
        #region 活动界面
        响应活动和首次充值按钮界面,
        进入活动奖励界面,
        活动奖励排名界面,
        进入首次充值界面,
        首次充值购买按钮点击,
        #endregion
        #region 商店界面
        打开商店界面UI,
        更多商品,
        购买了一个商品,
        #endregion
        #region 体力界面
        打开体力界面UI,
        用货币购买道具体力,
        #endregion
        #region 购买道具界面
        打开购买道具界面,
        购买了一个道具,
        #endregion
        #region 游戏失败是否继续游戏界面
        游戏失败是否继续游戏界面,
        #endregion
        #region///郑阳
        //选择关卡界面下方三个按钮
        打开好友消息界面,
        打开任务列表界面,
        打开地图选择界面,
        打开每日奖励界面,
        新的好友消息,
        //游戏中设置界面不带首页按钮
        打开游戏中的设置界面,
        //消息界面
        接受一个好友赠送的体力,
        赠送好友体力,
        //任务界面
        完成一个任务,
        //首页每日奖励界面
        领取今日奖励,
        //退出游戏确认界面
        退出游戏确认界面,
        #endregion
        购买商品成功,//购买游戏商品成功时的显示（包含体力和商品界面的商品）
        获得任务奖励或者活动奖励,//当任务完成或者侯东完成时获得的奖励从服务器发送玩家
        购买道具成功,//购买游戏道具成功时的显示（包含6中物品，游戏中的道具与三种特殊蔬菜）
        刷新道具数量,//当有道具被被改变时发送此消息
        体力恢复,

        体力扣除,

        使用道具,

        更新胜利关卡信息,

        更新失败关卡信息,

        消耗金币,
        看视频,//看视频可以获得移动步数和时间的加成

        连接FackBook,//连接FackBook登录账号
        FackBook邀请好友,//通关过账号邀请好友一起玩

        退出FackBook,//退出自己的FackBook账号
        Reconnect,//游戏过程中联网
        Redirect,
        ggn,//获取get gamecenture name
        seg,//成功进入游戏
        config,//确认购买
        ads//统计看视频次数



    }
}

